package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.OrderInfoMapper;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author 李旭
 * @date 2021/10/29 10:09
 * @Description:
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    //生成支付表   （财务使用）
    @Override
    public PaymentInfo insert(Long orderId, PaymentType paymentType) {
        //1:先查询是否已经生成了支付表 （防止重复保存支付表）幂等性问题

        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId));
        if(null != paymentInfo){
            //1.1已经生成了支付表
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfoMapper.updateById(paymentInfo);
        }else{
            //1.2 未生成支付表
            paymentInfo = new PaymentInfo();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            //对外业务编号
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    @Override
    public PaymentInfo selectPayment(String outTradeNo) {
        return paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("out_trade_no", outTradeNo));
    }


    //更新支付表
    @Override
    public void updatePaymentInfo(Map<String, String> paramsMap) {
        //1:幂等性问题  查询支付表
        PaymentInfo paymentInfo = selectPayment(paramsMap.get("out_trade_no"));
        if(null != paymentInfo && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
            //2:更新支付表
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            //2.1 银行流水
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
            //2.2 回调时间
            try {
                paymentInfo.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .parse(paramsMap.get("notify_time")));
                //2.3 回调内容
                paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paymentInfoMapper.updateById(paymentInfo);
            //3:发消息MQ 让MQ通知订单 更新订单状态
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                    MqConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());
        }
    }
    @Autowired
    private RabbitService rabbitService;

    /**
     * {gmt_create=2021-10-29 14:31:42,
     * charset=utf-8,
     * gmt_payment=2021-10-29 14:31:55,
     * notify_time=2021-10-29 14:31:56,
     * subject=Redmi K30 5G双模 120Hz流速屏 骁龙765G 30W快充 6GB+128GB 深海微光 游戏智能手机 小米 红米 Apple iPhone 11 (A2223) 64GB 红色 移动联,
     * sign=V4yotCaUYSC/oP8VPs4E9We6GjU8mntXu/vj/YjgAz3uyhC8td42CoZNlfl2TwxuoOVo9gzCs5U5OOOmt7zGVjqzhSuzbcZ/Xkm+j/K/LESy5ctbPLCncGF/x8Jz4K6ZzzMUdzAlMgozLyJL66lFsc8QKVXR4hHXMlTdUZf7o9l0iYUfghoAlL/fnP2PnMXTtJQBBlQ6a9yXPPnxut6KfeBAl2kKM1kI1AZ3+8aj1vdg3s3/8sfz25HTR+wbwUPQoTveR2tlenaZHbYNlD9Nu9k3EhW8IUJZEyEVONTbSoQfwm01XUhkddX6ufiG4CKQRVu4sWkFvCpUDxMa8cjumQ==,
     * buyer_id=2088102181130586,
     * invoice_amount=452214.00,
     * version=1.0,
     * notify_id=2021102900222143155030580518663905,
     * fund_bill_list=[
     *        {"amount":"452214.00",
     * 	"fundChannel":"ALIPAYACCOUNT"}
     * 	],
     * notify_type=trade_status_sync,
     * out_trade_no=ATGUIGU163513004877371345,
     * total_amount=452214.00,
     * trade_status=TRADE_SUCCESS,
     * trade_no=2021102922001430580501752383,
     * auth_app_id=2016102100732915,
     * receipt_amount=452214.00,
     * point_amount=0.00,
     * app_id=2016102100732915,
     * buyer_pay_amount=452214.00,
     * sign_type=RSA2,
     * seller_id=2088102180533564}
     *
     *
     *
     */
}
